package com.gable.exhibition.service.impl;

import com.gable.common.util.ChineseToEnglish;
import com.gable.common.util.MD5Util;
import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.UUIDGenerator;
import com.gable.exhibition.dao.HospitalDao;
import com.gable.exhibition.dao.UserDao;
import com.gable.exhibition.model.Hospital;
import com.gable.exhibition.model.User;
import com.gable.exhibition.service.HospitalService;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.HospitalView;
import com.gable.exhibition.view.ImportExcelHospitalModel;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Lesson on 2018/2/8.
 */
@Service("hospitalService")
public class HospitalServiceImpl implements HospitalService {

    Logger logger = Logger.getLogger(this.getClass());


    @Autowired
    HospitalDao hospitalDao;

    @Autowired
    UserDao userDao;

    @Override
    public ReturnResultUtil queryHospitalList(HospitalView hospitalView) {
        int count = hospitalDao.queryHospitalCount(hospitalView);
        List<HospitalView> list = hospitalDao.queryHospitalList(hospitalView);
        HospitalView hospitalView1 = new HospitalView();
        hospitalView1.setCount(count);
        hospitalView1.setList(list);
        return new ReturnResultUtil(200, MessageUtil.QUERYSUCCESS,hospitalView1);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil addOrUpdateHospital(HospitalView hospitalView) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int count = hospitalDao.checkHospitalName(hospitalView);
        if(count > 0){
            return new ReturnResultUtil(500,MessageUtil.HOSPITALNAMEDOESTEXIST);
        }

        int result = 0;
        if(hospitalView.getHospitalId() == null){
            hospitalView.setHospitalId(UUIDGenerator.getUniqueLong());
            result = hospitalDao.insertSelective(hospitalView);
            if(result > 0){
                User user = new User();
                user.setUserId(UUIDGenerator.getUniqueLong());
                user.setTag(1001L);
                user.setType(1101L);
                String userName = ChineseToEnglish.getPinYinHeadChar(hospitalView.getHospitalName())+"_admin";
                user.setUserName(userName);
                String password = MD5Util.md5("123456");
                user.setPassword(password);
                user.setRealName("医院管理员");
                user.setHospitalId(hospitalView.getHospitalId());
                user.setRemark("默认生成医院管理员");
                user.setCreateTime(df.format(new Date()));
                user.setCreatePerson(hospitalView.getCreatePerson());
                user.setIsDel(0);
                userDao.insertSelective(user);
            }
        }else{
            result = hospitalDao.updateByPrimaryKeySelective(hospitalView);
        }
        if(result>0){
            return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
        }
        return new ReturnResultUtil(200,MessageUtil.SAVEFAIL);
    }

    @Override
    public ReturnResultUtil queryHospitalInfo(Long hospitalId) {
        HospitalView hospitalView = hospitalDao.queryHospitalInfo(hospitalId);
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,hospitalView);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ReturnResultUtil saveHospitalByExcel(List<ImportExcelHospitalModel> list, User user) {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int count = 0;
        for(ImportExcelHospitalModel h : list){
            Hospital hospital = new Hospital();
            hospital.setHospitalId(UUIDGenerator.getUniqueLong());
            hospital.setHospitalName(h.getHospitalName());
            hospital.setHospitalCode(h.getHospitalCode());
            hospital.setProvinceId(h.getProvinceId());
            hospital.setCityId(h.getCityId());
            hospital.setAreaId(h.getAreaId());
            hospital.setIsDel(0);
            hospital.setAddress(h.getAddress());
            hospital.setHospitalContacts(h.getHospitalContacts());
            hospital.setHospitalPhone(h.getHospitalPhone());
            hospital.setRemark(h.getRemark());
            hospital.setCreatePerson(user.getUserId());
            hospital.setCreateTime(sdf.format(new Date()));
            int result = hospitalDao.insertSelective(hospital);
            if(result > 0){
                User users = new User();
                users.setUserId(UUIDGenerator.getUniqueLong());
                users.setTag(1001L);
                users.setType(1101L);
                String userName = ChineseToEnglish.getPinYinHeadChar(hospital.getHospitalName())+"_admin";
                users.setUserName(userName);
                String password = MD5Util.md5("123456");
                users.setPassword(password);
                users.setRealName("医院管理员");
                users.setHospitalId(hospital.getHospitalId());
                users.setRemark("默认生成医院管理员");
                users.setCreateTime(sdf.format(new Date()));
                users.setCreatePerson(hospital.getCreatePerson());
                users.setIsDel(0);
                userDao.insertSelective(users);
                count++;
            }
        }
        if(list.size() != count){
            ImportExcelHospitalModel importExcelHospitalModel= null;
            importExcelHospitalModel.getAddress();
        }
        return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
    }

    @Override
    public ReturnResultUtil queryHospitalListBySelect(HospitalView hospitalView) {
        HospitalView hv = this.gcj02_To_Bd09(hospitalView.getMapY(), hospitalView.getMapX());
        double longitude = hv.getMapX();
        double latitude = hv.getMapY();
        //先计算查询点的经纬度范围
        double r = 6371;//地球半径千米
        double dis = 30;//10千米距离
        double dlng =  2*Math.asin(Math.sin(dis/(2*r))/Math.cos(latitude*Math.PI/180));
        dlng = Math.abs(dlng*180/Math.PI);//角度转为弧度
        double dlat = dis/r;
        dlat = dlat*180/Math.PI;
        double minlat =latitude-dlat;
        double maxlat = latitude+dlat;
        double minlng = longitude -dlng;
        double maxlng = longitude + dlng;

        Map map = new HashMap();
        map.put("minlat",minlat);
        map.put("maxlat",maxlat);
        map.put("minlng",minlng);
        map.put("maxlng",maxlng);
        map.put("longitude",longitude);
        map.put("latitude",latitude);
        List<Hospital> list = hospitalDao.queryHospitalListBySelect(map);
        return new ReturnResultUtil(200,MessageUtil.QUERYSUCCESS,list);
    }

    public HospitalView gcj02_To_Bd09(double gg_lat, double gg_lon) {
        double x = gg_lon, y = gg_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI);
        double bd_lon = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;
        HospitalView hospitalView = new HospitalView();
        hospitalView.setMapX(bd_lon);
        hospitalView.setMapY(bd_lat);
        return hospitalView;
    }

}
